/*
 * @lc app=leetcode.cn id=2055 lang=typescript
 *
 * [2055] 蜡烛之间的盘子
 */

// @lc code=start
function platesBetweenCandles(s: string, queries: number[][]): number[] {
  const n = s.length;
  // 统计每个位置盘子的前缀和
  const preSum = new Array(n).fill(0);
  for (let i = 0, sum = 0; i < n; i++) {
    if (s[i] === '*') {
      sum++;
    }
    preSum[i] = sum;
  }
  // 计算每个点左边的第一个蜡烛位置
  const left = new Array(n).fill(0);
  for (let i = 0, l = -1; i < n; i++) {
    if (s[i] === '|') {
      l = i;
    }
    left[i] = l;
  }
  // 计算每个点右边的第一个蜡烛位置
  const right = new Array(n).fill(0);
  for (let i = n - 1, r = -1; i >= 0; i--) {
    if (s[i] === '|') {
      r = i;
    }
    right[i] = r;
  }

  const m = queries.length;
  const ans = new Array(m);
  // 枚举查询点，按位置查询两点之间的盘子数
  for (let i = 0; i < m; i++) {
    const [l, r] = queries[i];
    // 查询点最近的两个蜡烛位置
    const leftPoint = right[l];
    const rightPoint = left[r];
    ans[i] =
      leftPoint === -1 || rightPoint === -1 || leftPoint >= rightPoint
        ? 0
        : preSum[rightPoint] - preSum[leftPoint];
  }

  return ans;
}
// @lc code=end
